package com.example.springbootcaffeinedemo.common;
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/04/17  19:19
 * @Description: 缓存添加策略之手动异步加载
 */
public class CaffeineCacheAddPolicy3 {
    private static Object createObject(String key){
        return "hello caffeine 2023";
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        AsyncCache<String, Integer> cache = Caffeine.newBuilder().buildAsync();
        String key="毒舌律师";
        //1、返回一个future对象(源码中：CompletableFuture类实现了Future接口)
        CompletableFuture<Integer> future = cache.get(key, name -> {//key作为入参，传值给name,即name="毒舌律师"
            System.out.println("name电影：" + name);
            return 2023;
        });
        //2、调用future对象的get()方法会一直阻塞直到得到返回，和多线程的submit一样
        Integer age = future.get();
        System.out.println("year: " +age);
    }
}
